package cn.sfrog.project.biz.admin.service.impl;

import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.core.domain.model.LoginUser;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.enums.UserStatus;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.framework.web.service.TokenService;
import cn.sfrog.project.biz.admin.domain.BizUserAccount;
import cn.sfrog.project.biz.admin.domain.BizUserGiveAwayRecord;
import cn.sfrog.project.biz.admin.domain.vo.BizUserGiveAwayRecordFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserGiveAwayRecordQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserGiveAwayRecordVO;
import cn.sfrog.project.biz.admin.enums.BizUserTradeTypeEnum;
import cn.sfrog.project.biz.admin.mapper.BizUserGiveAwayRecordMapper;
import cn.sfrog.project.biz.admin.service.IBizUserGiveAwayRecordService;
import cn.sfrog.project.biz.admin.service.IBizUserTradeRecordService;
import cn.sfrog.project.biz.web.vo.account.AppUserGiveAwayFormVO;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import cn.sfrog.system.mapper.SysUserMapper;
import cn.sfrog.system.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * 转赠记录Service业务层处理
 */
@Service
public class BizUserGiveAwayRecordServiceImpl extends ServiceImpl<BizUserGiveAwayRecordMapper, BizUserGiveAwayRecord> implements IBizUserGiveAwayRecordService {
    @Resource
    private BizUserGiveAwayRecordMapper bizUserGiveAwayRecordMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IBizUserTradeRecordService bizUserTradeRecordService;
    @Autowired
    private RedisCache redisCache;



    /**
     * 查询转赠记录
     *
     * @param id 转赠记录主键
     * @return 转赠记录
     */
    @Override
    public BizUserGiveAwayRecordVO selectBizUserGiveAwayRecordById(Long id) {
        return bizUserGiveAwayRecordMapper.selectBizUserGiveAwayRecordById(id);
    }

    /**
     * 查询转赠记录列表
     *
     * @param query 转赠记录
     * @return 转赠记录
     */
    @Override
    public List<BizUserGiveAwayRecordVO> selectBizUserGiveAwayRecordList(BizUserGiveAwayRecordQueryVO query) {
        return bizUserGiveAwayRecordMapper.selectBizUserGiveAwayRecordList(query);
    }

    /**
     * 新增转赠记录
     *
     * @param form 转赠记录
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizUserGiveAwayRecord(BizUserGiveAwayRecordFormVO form) {
        BizUserGiveAwayRecord bizUserGiveAwayRecord = new BizUserGiveAwayRecord();
        BeanUtils.copyProperties(form, bizUserGiveAwayRecord);
        bizUserGiveAwayRecord.setCreateTime(new Date());
        bizUserGiveAwayRecord.setCreateBy(SecurityUtils.getUsername());
        bizUserGiveAwayRecord.setUpdateTime(new Date());
        bizUserGiveAwayRecord.setUpdateBy(SecurityUtils.getUsername());
        return bizUserGiveAwayRecord.insert();
    }

    /**
     *
     * 修改转赠记录
     *
     * @param form 转赠记录
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizUserGiveAwayRecord(BizUserGiveAwayRecordFormVO form) {
        BizUserGiveAwayRecord bizUserGiveAwayRecord = new BizUserGiveAwayRecord();
        BeanUtils.copyProperties(form, bizUserGiveAwayRecord);
        bizUserGiveAwayRecord.setUpdateTime(new Date());
        bizUserGiveAwayRecord.setUpdateBy(SecurityUtils.getUsername());
        return bizUserGiveAwayRecord.updateById();
    }

    /**
     * 批量删除转赠记录
     *
     * @param ids 需要删除的转赠记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizUserGiveAwayRecordByIds(Long[] ids) {
            return BizUserGiveAwayRecord.DAO.delete(Wrappers.lambdaQuery(BizUserGiveAwayRecord.class).in(BizUserGiveAwayRecord::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
        return BizUserGiveAwayRecord.DAO.update(Wrappers.lambdaUpdate(BizUserGiveAwayRecord.class).in(BizUserGiveAwayRecord::getId, (Object[]) vo.getIds()).set(BizUserGiveAwayRecord::getStatus, vo.getStatus()));
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean saveUserGiveAwayRecord(AppUserGiveAwayFormVO form) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        BigDecimal formGiveAwayAmount = form.getGiveAwayAmount();
        //通过转赠接收人手机号查询用户
        //SysUser sysUser = sysUserMapper.selectAppUserByPhone(form.getReceiverUserPhone());
        SysUser sysUser = sysUserMapper.selectAppUserByPhoneAndType(form.getReceiverUserPhone(),form.getUserType());
        if(StringUtils.isNull(sysUser) || StringUtils.equals(sysUser.getDelFlag(), UserStatus.DELETED.getCode()) ||
                StringUtils.equals(sysUser.getStatus(), UserStatus.DISABLE.getCode())){
            throw new ApiException("用户不存在");
        }
        if(sysUser.getUserId().equals(user.getUserId())){
            throw new ApiException("不允许转赠自己");
        }
        LambdaQueryWrapper<BizUserAccount> lambdaQueryWrapper = new LambdaQueryWrapper<BizUserAccount>()
                .eq(BizUserAccount::getUserId,user.getUserId());
        BizUserAccount currentUserAccount = BizUserAccount.DAO.selectOne(lambdaQueryWrapper);

        LambdaQueryWrapper<BizUserAccount> queryWrapper = new LambdaQueryWrapper<BizUserAccount>()
                .eq(BizUserAccount::getUserId,sysUser.getUserId());
        BizUserAccount receiverUserAccount = BizUserAccount.DAO.selectOne(queryWrapper);

        //赠送发起人账户可用余额
        BigDecimal ableAmount = currentUserAccount.getAccountBalance();
        //赠送发起人提成余额
        BigDecimal ableCommissionAmount = currentUserAccount.getCommissionAmount().subtract(currentUserAccount.getFreezeAmount());


        if(formGiveAwayAmount.compareTo(ableAmount.add(ableCommissionAmount)) == 1){
            throw new ApiException("账户可用余额不足,请核对转赠数量");
        }
        // 1.如果转赠金额 < 账户可用余额（不包括赠送金额） 则直接扣减账户余额
        if(formGiveAwayAmount.compareTo(ableAmount) < 1){
            currentUserAccount.setAccountBalance(currentUserAccount.getAccountBalance().subtract(formGiveAwayAmount));

        }else {
            //2.（转赠金额 > 账户可用余额） 并且 （转赠金额 < 提成金额-冻结金额）
            currentUserAccount.setAccountBalance(currentUserAccount.getAccountBalance().subtract(ableAmount));
            //剩下的从系统赠送金额中扣减
            BigDecimal subGiveAwayAmount = formGiveAwayAmount.subtract(ableAmount);
            //currentUserAccount.setGiveAwayAmount(currentUserAccount.getGiveAwayAmount().subtract(subGiveAwayAmount));
            currentUserAccount.setCommissionAmount(currentUserAccount.getCommissionAmount().subtract(subGiveAwayAmount));
        }
        currentUserAccount.setConsumeAmount(currentUserAccount.getConsumeAmount().add(formGiveAwayAmount));
        currentUserAccount.updateById();
        //更新用户的陪护豆余额
        user.setEscortBeanCount(currentUserAccount.getAccountBalance().add(currentUserAccount.getGiveAwayAmount()).add(currentUserAccount.getCommissionAmount()));
        sysUserMapper.updateUser(user);
        loginUser.setUser(user);
        tokenService.refreshToken(loginUser);


        //赠送接收人
        receiverUserAccount.setAccountBalance(receiverUserAccount.getAccountBalance().add(formGiveAwayAmount));
        receiverUserAccount.updateById();
        SysUser receiverUser = new SysUser();
        receiverUser.setUserId(sysUser.getUserId());
        receiverUser.setEscortBeanCount(receiverUserAccount.getAccountBalance().add(receiverUserAccount.getGiveAwayAmount()).add(receiverUserAccount.getCommissionAmount()));
        sysUserMapper.updateUser(receiverUser);


        //转增记录
        BizUserGiveAwayRecord giveAwayRecord = new BizUserGiveAwayRecord();
        giveAwayRecord.setReceiverUserId(sysUser.getUserId());
        giveAwayRecord.setReceiverUserPhone(form.getReceiverUserPhone());
        String giveAwaySerialNumber = redisCache.buildGiveAwaySerialNumber();
        giveAwayRecord.setSerialNumber(giveAwaySerialNumber);
        giveAwayRecord.setSponsorUserId(user.getUserId());
        giveAwayRecord.setGiveAwayAmount(formGiveAwayAmount);
        giveAwayRecord.setGiveAwayTime(DateUtils.getNowDate());
        boolean insert = giveAwayRecord.insert();




        //用户交易记录
        bizUserTradeRecordService.saveUserTradeRecord(user.getUserId(),formGiveAwayAmount.negate(), BizUserTradeTypeEnum.GIVE_AWAY.getCode(),giveAwaySerialNumber,"转赠/"+sysUser.getNickName());
        // TODO: 2022/9/22 收到转赠陪护豆的人需不需要交易记录
        bizUserTradeRecordService.saveUserTradeRecord(sysUser.getUserId(),formGiveAwayAmount, BizUserTradeTypeEnum.GIVE_AWAY.getCode(),giveAwaySerialNumber,"转赠/"+user.getNickName());
        return insert;
    }


}
